<template>
  <div>
    <div class="search-bar">
      <div class="search-fields">
        <el-input v-model="searchName" placeholder="请输入分类名称" style="width: 220px; margin-right: 12px;" clearable />
        <el-select v-model="searchStatus" placeholder="请选择是否启用" style="width: 220px; margin-right: 12px;" clearable>
          <el-option label="全部" :value="''" />
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
        <el-button type="primary" @click="fetchData" style="margin-right: 8px;">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="openDialog(null, 'addRoot')" style="margin-left: 16px;">+ 添加分类</el-button>
      </div>
      <el-divider />
    </div>
    <el-table
      :data="tableData"
      row-key="id"
      border
      stripe
      default-expand-all
      :tree-props="{ children: 'children' }"
      style="width: 100%; margin-top: 0;"
    >
      <el-table-column prop="classifyName" label="分类" min-width="120" />
      <el-table-column prop="orderById" label="排序" min-width="80" />
      <el-table-column prop="materialName" label="物料/产品" min-width="120" />
      <el-table-column prop="status" label="是否启用" min-width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status === 1" type="success">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="160" />
      <el-table-column label="操作" min-width="140">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="openDialog(row, 'edit')">修改</el-button>
          <el-button type="success" link size="small" @click="openDialog(row, 'addChild')">+新增</el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="getDialogTitle()" width="500px">
      <el-form :model="dialogForm" :rules="rules" ref="dialogFormRef" label-width="100px">
        <el-form-item label="父分类" prop="parentId">
          <el-cascader
            v-if="dialogType === 'addChild'"
            v-model="dialogForm.parentId"
            :options="parentCascaderOption"
            :props="{ 
              checkStrictly: true, 
              emitPath: false,
              label: 'classifyName', 
              value: 'id',
              children: 'children'
            }"
            placeholder="请选择父分类"
            disabled
            style="width: 100%"
          />
          <el-cascader
            v-else-if="dialogType === 'edit'"
            v-model="dialogForm.parentId"
            :options="cascaderOptions"
            :props="{ 
              checkStrictly: true, 
              emitPath: false,
              label: 'classifyName', 
              value: 'id',
              children: 'children',
              disabled: item => disabledOptions.includes(item.id)
            }"
            clearable
            placeholder="请选择父分类"
            style="width: 100%"
          />
          <el-cascader
            v-else
            v-model="dialogForm.parentId"
            :options="cascaderOptions"
            :props="{ 
              checkStrictly: true, 
              emitPath: false,
              label: 'classifyName', 
              value: 'id',
              children: 'children'
            }"
            clearable
            placeholder="请选择父分类"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="classifyName">
          <el-input v-model="dialogForm.classifyName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderById">
          <el-input-number v-model="dialogForm.orderById" :min="1" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="物料/产品" prop="materialName">
          <el-radio-group v-model="dialogForm.materialName">
            <el-radio label="物料">物料</el-radio>
            <el-radio label="产品">产品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue';
import { ElTable, ElTableColumn, ElTag, ElInput, ElButton, ElSelect, ElOption, ElDivider, ElDialog, ElForm, ElFormItem, ElInputNumber, ElRadio, ElRadioGroup, ElCascader, ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const tableData = ref([]);
const searchName = ref('');
const searchStatus = ref('');

// 弹窗相关
const dialogVisible = ref(false);
const dialogForm = ref({ id: 0, parentId: 0, classifyName: '', orderById: 1, materialName: '物料', status: 1 });
const dialogFormRef = ref();
const treeSelectData = ref([]);
const dialogType = ref('addRoot'); // 'addRoot'(添加根分类) | 'addChild'(添加子分类) | 'edit'(修改)

// 专门用于添加子分类时展示的父分类选项
const parentCascaderOption = ref([]);

// 禁用选项列表（编辑时禁用自己及子节点）
const disabledOptions = ref([]);

// Cascader专用选项数据，添加根节点选项
const cascaderOptions = computed(() => {
  // 创建一个深拷贝，以免修改原始数据
  const options = JSON.parse(JSON.stringify(treeSelectData.value || []));
  // 添加"作为根节点"选项
  options.unshift({
    id: 0,
    classifyName: '作为根节点',
    children: []
  });
  return options;
});

const rules = {
  classifyName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  orderById: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  materialName: [{ required: true, message: '请选择物料/产品', trigger: 'change' }],
  status: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
};

// 获取节点及其所有子孙节点的ID
const getNodeAndChildrenIds = (nodeId, nodes) => {
  const result = [];
  
  const findNode = (id, nodeList) => {
    for (const node of (nodeList || [])) {
      if (node.id === id) {
        result.push(node.id);
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => {
            result.push(child.id);
            if (child.children && child.children.length > 0) {
              findNode(child.id, [child]);
            }
          });
        }
        return true;
      }
      
      if (node.children && node.children.length > 0) {
        if (findNode(id, node.children)) {
          return true;
        }
      }
    }
    return false;
  };
  
  findNode(nodeId, nodes);
  return result;
};

const fetchData = async () => {
  try {
    const res = await axios.get('/api/MasterData/GetTree');
    // 兼容 res 结构
    const data = Array.isArray(res) ? res : (res.data || res || []);
    const filterTree = (nodes) => {
      return (Array.isArray(nodes) ? nodes : []).map(node => {
        const children = Array.isArray(node.children) ? filterTree(node.children) : [];
        const nameMatch = searchName.value ? (node.classifyName || '').includes(searchName.value) : true;
        const statusEmpty = searchStatus.value === '' || searchStatus.value === null || typeof searchStatus.value === 'undefined';
        const statusMatch = statusEmpty ? true : Number(node.status) === Number(searchStatus.value);
        if ((nameMatch && statusMatch) || children.length > 0) {
          return { ...node, children };
        }
        return null;
      }).filter(Boolean);
    };
    tableData.value = filterTree(data);
    treeSelectData.value = JSON.parse(JSON.stringify(data));
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

const resetSearch = () => {
  searchName.value = '';
  searchStatus.value = '';
  fetchData();
};

const getDialogTitle = () => {
  switch(dialogType.value) {
    case 'edit': return '修改分类';
    case 'addChild': return '添加子分类';
    case 'addRoot': return '添加根分类';
    default: return '分类信息';
  }
};

const openDialog = (row = null, type = 'addRoot') => {
  dialogType.value = type;

  if (type === 'edit' && row) {
    // 编辑模式
    dialogForm.value = { ...row };
    // 获取当前节点及其所有子节点ID，这些节点将在选择器中被禁用
    disabledOptions.value = getNodeAndChildrenIds(row.id, treeSelectData.value);
  } else if (type === 'addChild' && row) {
    // 添加子节点模式 - 父分类固定为当前节点，不可更改
    dialogForm.value = { 
      id: 0, 
      parentId: row.id, 
      classifyName: '', 
      orderById: 1, 
      materialName: '物料', 
      status: 1 
    };
    
    // 设置父分类选项，只包含当前行，用于展示
    parentCascaderOption.value = [{
      id: row.id,
      classifyName: row.classifyName,
      children: []
    }];
    
    // 不需要设置禁用选项，因为整个选择器都被禁用了
    disabledOptions.value = [];
  } else {
    // 添加根节点模式
    dialogForm.value = { 
      id: 0, 
      parentId: 0, 
      classifyName: '', 
      orderById: 1, 
      materialName: '物料', 
      status: 1 
    };
    disabledOptions.value = [];
  }
  
  dialogVisible.value = true;
  nextTick(() => {
    dialogFormRef.value && dialogFormRef.value.clearValidate();
  });
};

const submitDialog = () => {
  dialogFormRef.value.validate(async (valid) => {
    if (!valid) return;
    // 组装参数
    const param = { ...dialogForm.value };
    // 处理后端需要的字段
    param.createTime = param.createTime || new Date().toISOString();
    try {
      await axios.post('/api/MasterData/CreateUpdateMaterialCatalog', param);
      ElMessage.success('操作成功');
      dialogVisible.value = false;
      fetchData();
    } catch (e) {
      ElMessage.error('操作失败');
    }
  });
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除分类 "${row.classifyName}" ${row.children && row.children.length > 0 ? '及其所有子分类' : ''}吗？`,
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.delete(`/api/MasterData/DeleteMaterialCatalog?id=${row.id}`);
      ElMessage.success('删除成功');
      fetchData(); // 重新加载数据
    } catch (error) {
      console.error('删除失败', error);
      ElMessage.error('删除失败：' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }).catch(() => {
    // 用户取消删除时不显示任何消息
  });
};

onMounted(fetchData);
</script>

<style scoped>
.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}
.search-bar {
  background: #fafbfc;
  padding: 18px 24px 8px 24px;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
}
.search-fields {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 8px;
}
.el-tag {
  font-size: 14px;
}
.el-button[link] {
  padding: 0 6px;
  font-size: 13px;
  transition: color 0.2s;
}
.el-button[link]:hover {
  text-decoration: underline;
  opacity: 0.8;
}
</style>

